<?php

/**
 * @category   mediad2
 * @package    Mediad2_Service
 */
class Mediad2_Service_Admin_Role extends Mediad2_Service_Abstract
{
	/**
	 * 初始化
	 */
	public function init()
	{
		$this->setMapper('Mediad2_Mapper_Role');
		$this->setModel('Mediad2_Model_Role');
	}
	
	/**
	 * 批量删除指定的角色记录
	 *
	 * @param array of $roleId
	 * @return boolean return true if no error.
	 */
	public function deleteBatch(array $arrayRoleId)
	{
		if ( count($arrayRoleId) == 0 ) {
			return false;
		}
	
		//构造where条件
		$where = 'roleId in ( ' . implode(",", $arrayRoleId) . ')';
	
		$mapper = $this->getMapper();
		$dao = $mapper->getDao();
		$result = $dao->delete($where);
		if ($result > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 返回符合条件的ACL角色
	 *
	 * @param integer $pageIndex
	 * @param integer $pageNum
	 * @param string $where
	 * @param string $order
	 * @param boolean $returnArray
	 * @return array MediadOffer_Model_GloRole
	 */
	public function fetchAclRole($pageIndex = 1, $pageNum = 20, $where = null, $order = null, $returnArray = false)
	{
		$roles = $this->fetchAll();		
		$result = $this->sortAclRole($roles->getData());
		return $result;
	}
	
	/**
	 * 根据parent对角色进行排序
	 *
	 * @param array $originalRoles
	 * @return array - the array data include 'code' and 'parents'
	 */
	private function sortAclRole(array $originalRoles) {
		$tempRoles= array();
		$result = array();
		while(count($originalRoles)>0) {
			foreach ($originalRoles as $key => $value) {
				$code = $value->getRoleCode();
				$parents = $value->getParentRoleCode();
				if (empty($parents)) {
					$tempRoles[] = $code;
					$result[] = array('code'=>$code, 'parents'=>$parents);
					unset($originalRoles[$key]);
				} else {
					$tempParents = explode(',', $parents);
					foreach ($tempParents as $key1 => $value1) {
						if (!in_array($value1,$tempRoles)) {
							break;
						} else {
							unset($tempParents[$key1]);
						}
					}
					if (empty($tempParents)) {
						$tempRoles[] = $code;
						$result[] = array('code'=>strtolower($code), 'parents'=>strtolower($parents));
						unset($originalRoles[$key]);
					}
				}
			}
		}
		return $result;
	}
	
}